<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleEditTabClick">

      <el-tab-pane label="任务办理" name="approval"  v-if="processInstanceInfo.activeTaskForm.id">
        <approval :form-create-info="formCreateInfo"
                  :task-approval-form="taskApprovalForm"
                  :task-id="processInstanceInfo.activeTaskForm.id"
                  @complete="handleComplete"
                  @reject="handleReject"
                  @selectApprover="selectApprover"></approval>
      </el-tab-pane>


      <el-tab-pane label="表单信息" name="formMessage">
        <el-card class="box-card" shadow="hover" v-for="(item,index) in completeTaskFormList" :key=index style="margin-top: 30px" v-if="isNotBlack(item.formFields) || isNotBlack(item.formCustomCreatePath)">
          <div slot="header" class="clearfix">
            <span>{{ item.name }}</span>
          </div>
          <template v-if="isNotBlack(item.formFields) && item.formType === 0">
            <el-col :span="20" :offset="2">
              <form-create v-model="fApi" :rule="item.formFields" :option="item.formOption" :value.sync="item.formVariables"></form-create>
            </el-col>
          </template>
          <template v-if="item.formType === 1 && isNotBlack(item.formCustomCreatePath)">
            <dynamic-component :uri="item.formCustomCreatePath" :form-data="item.formVariables"></dynamic-component>
          </template>
        </el-card>
      </el-tab-pane>


      <el-tab-pane label="流转记录" name="transferRecords">
        <div>
          <el-row>
            <el-col :span="16" :offset="4">
              <el-timeline>
                <el-timeline-item v-for="(item, index) in processInstanceInfo.bpmTaskVoList" :key="index"
                                  :icon="getIcon(item)" :type="getType(item)">
                  <p style="font-weight: 700">任务：{{ item.name }}</p>
                  <el-card :body-style="{ padding: '10px' }">

                    <div>
                      <label v-if="item.assignee" style="font-size: 15px">审批人：</label>
                      <label style="font-weight: normal; font-size: 15px">
                        {{ item.assignee }}
                      </label>
                    </div>


                    <div>
                      <label v-if="item.startTime" style="font-size: 15px;font-weight: bold">创建时间：</label>
                      <label style="font-weight: normal; font-size: 15px">
                        {{ item.startTime }}
                      </label>
                    </div>

                    <div>
                      <label v-if="item.endTime" style="font-size: 15px">
                        审批时间：
                      </label>
                      <label v-if="item.endTime" style="font-weight: normal; font-size: 15px">
                        {{ item.endTime }}
                      </label>
                    </div>

                    <div>
                      <label v-if="item.useTime" style="font-size: 15px">
                        耗时：
                      </label>
                      <label v-if="item.useTime" style="font-weight: normal; font-size: 15px">
                        {{ item.useTime }}
                      </label>
                    </div>

                    <div>
                      <label v-if="item.taskState" style="font-size: 15px">
                        状态：
                      </label>
                      <label v-if="item.taskState" style="font-weight: normal; font-size: 15px">
                        {{ convertToChinese(item.taskState) }}
                      </label>
                    </div>

                    <div v-if="item.commentList && item.commentList.length > 0">
                      <div v-for="comment in item.commentList" :key="comment.id">

                        <el-tag type="success" style="margin-top: 15px">{{ convertToChinese(comment.type) }}</el-tag>
                        <el-tag type="info" style="margin-left: 20px;margin-top: 15px"> {{ comment.fullMessage }}</el-tag>
<!--                        <div>-->
<!--                          <label style="font-size: 15px">-->
<!--                            状态：-->
<!--                          </label>-->
<!--                          <label style="font-weight: normal; font-size: 15px">-->
<!--                            {{ comment.type }}-->
<!--                          </label>-->
<!--                        </div>-->
<!--                       <div>-->
<!--                         <label style="font-size: 15px">-->
<!--                           审批意见：-->
<!--                         </label>-->
<!--                         <label style="font-weight: normal; font-size: 15px">-->
<!--                           {{ comment.fullMessage }}-->
<!--                         </label>-->
<!--                       </div>-->
                      </div>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-col>
          </el-row>

        </div>
      </el-tab-pane>


      <el-tab-pane label="流程图" name="flowchart">
        <flow-chart ref="flowchart" :key="flowIndex" :current-canvas-xml="processInstanceInfo.bpmnXml"
                    :task-list="processInstanceInfo.bpmTaskVoList"></flow-chart>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>

import {getBpmProcessInstance} from "@/api/flowable/bpmProcessInstance";
import FlowChart from "@/views/flowable/bpmProcessDetail/flowChart.vue";
import formCreate from "@form-create/element-ui";
import {complete, reject} from "@/api/flowable/bpmTask";
import Approval from "@/views/flowable/bpmProcessDetail/approval.vue";
import DynamicComponent from "@/components/DynamicComponent/dynamicComponent.vue";

export default {
  name: "BpmProcessDetail",
  components: {DynamicComponent, Approval, FlowChart},
  data() {
    return {
      //激活标签页名称
      activeName: 'transferRecords',
      //流程实例信息
      processInstanceInfo: {
        bpmTaskVoList: [],
        bpmnXml: {},
        completeTaskForm:[],
        activeTaskForm:{}
      },
      flowIndex: 1,
      //加载动画
      dataLoad: false,
      //流程审批信息
      taskApprovalForm:{
        formDate:'',
        flowData:{
          assigneeName:null,
          assignee:null,
          comment:null,
        }
      },
      //流程表单信息
      formCreateInfo:{
        option: {},
        rule:[],
        value: {},
        formType:0,
        formCustomCreatePath:'',
      },
      completeTaskFormList:[],
      fApi: {},
      rules: {
        comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.loading = this.$loading({
      lock: true,
      text: "加载中",
      background: "rgba(0, 0, 0, 0.7)",
    });
    getBpmProcessInstance(this.$route.query.processInstanceId).then(res => {
      this.processInstanceInfo = res.data;
      console.log(this.processInstanceInfo);
      this.loading.close();
    })
  },
  methods: {
    handleEditTabClick(tab, event) {
      console.log(tab.name, event);
      if (tab.name == 'flowchart') {
        this.$nextTick(() => {
          // this.$refs.flowchart.currentCanvasXml =  this.processInstanceInfo.bpmnXml;
          this.$refs.flowchart.previewTemp();
        });
        this.flowIndex = this.flowIndex + 1;
      }else if(tab.name == 'approval'){
        this.formCreateInfo.option = JSON.parse(this.processInstanceInfo.activeTaskForm.formOption)
        this.formCreateInfo.rule = formCreate.parseJson(this.processInstanceInfo.activeTaskForm.formFields)
        this.formCreateInfo.value = JSON.parse(this.processInstanceInfo.activeTaskForm.formVariables) || {}
        this.formCreateInfo.formType = this.processInstanceInfo.activeTaskForm.formType
        this.formCreateInfo.formCustomCreatePath = this.processInstanceInfo.activeTaskForm.formCustomCreatePath
      }else if(tab.name == 'formMessage'){
        this.completeTaskFormList = [];
        this.$nextTick(()=>{
          this.processInstanceInfo.completeTaskForm.forEach(item=>{
            let newForm = {formFields:[],formOption:{},formVariables:{},name:'',formType:'',formCustomCreatePath:''};
            newForm.formFields = formCreate.parseJson(item.formFields);
            newForm.formOption = JSON.parse(item.formOption);
            newForm.formVariables = JSON.parse(item.formVariables);
            newForm.formType = item.formType;
            newForm.formCustomCreatePath = item.formCustomCreatePath;
            newForm.name = item.name;
            this.completeTaskFormList.push(newForm);
          })
        })
      }
    },
    getIcon(item) {
      if (item.taskState === 'Active') {
        return 'el-icon-time'
      }
      if (item.taskState === 'Completed') {
        return 'el-icon-check'
      }
      if (item.taskState === 3) {
        return 'el-icon-close'
      }
      if (item.taskState === 4) {
        return 'el-icon-remove-outline'
      }
      return ''
    },

    /** 获得任务对应的颜色 */
    getType(item) {
      if (item.taskState === 'Active') {
        return 'primary'
      }
      if (item.taskState === 'Completed') {
        return 'success'
      }
      if (item.taskState === 3) {
        return 'danger'
      }
      if (item.taskState === 4) {
        return 'info'
      }
      return ''
    },
    userAssigneeSelect(){

    },

    selectApprover(val){
      if(val&&val.length>0){
        this.taskApprovalForm.flowData.assignee=val[0].userId
        this.taskApprovalForm.flowData.assigneeName=val[0].nickName
      }
    },

    handleComplete(){
      let taskApprovalForm = {
        taskId: this.processInstanceInfo.activeTaskForm.id,
        formOption:JSON.stringify(this.formCreateInfo.option),
        formFields:formCreate.toJson(this.formCreateInfo.rule),
        formVariables:JSON.stringify(this.formCreateInfo.value),
        formCustomCreatePath:this.formCreateInfo.formCustomCreatePath,
        formType:this.formCreateInfo.formType,
        formDate: '',
        flowData: {
          assignee: this.taskApprovalForm.flowData.assignee,
          comment: this.taskApprovalForm.flowData.comment,
        }
      }
      complete(taskApprovalForm).then((res)=>{
        this.$message.success("提交成功");
        this.$router.push({
          path:'/bpm/bpmTask'
        })
      })
    },

    handleReject(){
      reject({
        taskId: this.processInstanceInfo.activeTaskForm.id,
        flowData: {
          assignee: null,
          comment: this.taskApprovalForm.flowData.comment,
        }
      }).then((res)=>{
        this.$message.success("驳回成功");
        this.$router.push({
          path:'/bpm/bpmTask'
        })
      })
    },
    convertToChinese(englishStatus) {
      const statusMap = {
        "Completed": "已完成",
        "Active": "活动",
        "Suspended": "已挂起",
        "Delegated": "已委派",
        "TransferTask": "已转办",
        "Approved": "已通过",
        "Returned": "已退回",
        "Rejected": "已驳回",
        "Transferred": "已转办",
        "Terminated": "已终止",
        "Withdrawn": "已撤回",
        "Not Found": "未找到"
      }; // 确保你的状态映射在这个对象中

      return statusMap[englishStatus] || '未找到对应的中文状态';
    },

    isNotBlack(obj) {
      if (obj === null || obj === undefined) {
        return false;
      }

      if (typeof obj === 'string') {
        return obj.trim() !== '';
      }

      if (obj.hasOwnProperty('length')) {
        return obj.length > 0;
      }

      return true;
    }

  }
};
</script>
